package com.example.thumbfromalbum;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private GridView lv;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    private void initView() {
        imageView = (ImageView) findViewById(R.id.iv);
    }

    public void click(View view) {
        ArrayList<HashMap<String, String>> thumb = getThumb();
        for (HashMap<String, String> stringStringHashMap : thumb) {
            String thumbnail_path = stringStringHashMap.get("thumbnail_path");
            String image_id_path = stringStringHashMap.get("image_id");
            Log.d("click", "click: imageUrl:" + image_id_path + "\n" + "thumbnail_path:" + thumbnail_path);
        }
    }

    private ArrayList<HashMap<String, String>> getThumb() {
        ArrayList<HashMap<String, String>> picturemaps = new ArrayList<>();
        HashMap<String, String> picturemap;
        ContentResolver contentResolver = this.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Thumbnails.DATA},
                null,
                null,
                MediaStore.Images.Thumbnails.DEFAULT_SORT_ORDER);
        assert cursor != null;

        if (cursor.moveToFirst()) {
            do {
                picturemap = new HashMap<>();
                picturemap.put("image_id_path", cursor.getInt(0) + "");
                picturemap.put("thumbnail_path", cursor.getString(1));
                picturemaps.add(picturemap);
            } while (cursor.moveToNext());
            cursor.close();
        }

        for (int i = 0; i < picturemaps.size(); i++) {
            picturemap = picturemaps.get(i);
            String image_id_path = picturemap.get("image_id_path");
            Cursor query = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.Media.DATA},
                    MediaStore.Audio.Media._ID + "=" + image_id_path,
                    null,
                    null);
            assert query != null;
            if (query.moveToFirst()) {
                do {
                    picturemap.put("image_id", query.getString(0));
                    picturemaps.set(i, picturemap);
                } while (query.moveToNext());
                query.close();
            }
        }
        return picturemaps;
    }
}
